<?php

namespace app\user\controller;

use app\common\controller\Front;
use app\common\logic\SendLogic;
use app\common\serve\User;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

/**
 * 登录、注册
 * Class passport
 * @package app\user\controller
 */
class Passport extends Front
{
    public function ajax_phone()
    {
        $phone = $this->request->param('phone', '');

        if (Db::name('user')->where(['phone' => trim($phone)])->count() > 0) {
            $this->error('此手机号已经被注册，请重新输入');
        }
        $this->success('success');
    }

    /**
     * @return bool|mixed
     */
    public function register()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post();

            if (!captcha_check($params['verify'], 1, config('captcha'))) {
                $this->error('图形验证码不正确！');
            }

            if (!checkPhone($params['phone'])) {
                $this->error('大陆手机号格式不正确！');
            }

            if (Db::name('user')->where(['phone' => $params['phone']])->count() > 0) {
                $this->error('大陆手机号已被注册！');
            }

            if (!checkSms($params['phone'], $params['scode'])) {
                $this->error(' 短信验证码不正确！');
            }

            if (!checkPass($params['password'])) {
                $this->error('密码格式必须是字母+数字8-20位之间');
            }

            $uid = Db::name('user')->where(['phone' => $params['invite']])->value('id');

            if ($uid < 1) {
                $this->error('推荐码不正确');
            }

            $params = [
                'phone' => $params['phone'],
                'password' => $params['password'],
                'time' => $this->request->time(),
                'ip' => $this->request->ip(),
                'way' => $this->isMobile() ? 2 : 1,
                'invite' => $uid
            ];

            $result = User::register($params);

            if (is_array($result) && $result['code'] == 1) {
                $this->success('注册成功！', url('user/index/index'));
            } else {
                $this->error($result['msg'], '');
            }

            return false;
        } else {
            if (is_login()) {
                $this->redirect('user/index/index');
            }
            $this->assign('ad', db('ad')->field('title,url,cover_id')->where(['unique_id' => 'register'])->order('id DESC')->find());


            $this->assign('invite', '');

            return $this->fetch();
        }
    }

    /**
     * 登录
     * @param string $username
     * @param string $password
     * @param string $verify
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post();

            if (isset($params['verify'])) {
                //验证码验证
                if (!captcha_check($params['verify'])) {
                    $this->error('验证码错误', '');
                }
            }

            if (!checkPhone($params['phone'])) {
                $this->error('大陆手机号格式不正确！');
            }

            if (Db::name('user')->where(['phone' => $params['phone']])->count() < 1) {
                $this->error('大陆手机号未注册！');
            }

            if (!checkPass($params['password'])) {
                $this->error('密码格式必须是字母+数字8-20位之间');
            }

            $uid = User::login($params['phone'], $params['password']);

            if ($uid > 0) {
                $url = session('http_referer') ? session('http_referer') : url('user/index/index');
                $this->success('登录成功！', $url);
            } else {
                switch ($uid) {
                    case -1:
                        $error = '用户不存在或被禁用！';
                        break; //系统级别禁用
                    case -2:
                        $error = '密码错误！';
                        break;
                    default:
                        $error = '未知错误！';
                        break; // 0-接口参数错误（调试阶段使用）
                }
                $this->error($error, '');
            }
        } else {
            session('http_referer', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
            if (is_login()) {
                $this->redirect('user/index/index');
            } else {
                $this->assign('ad', db('ad')->field('title,url,cover_id')->where(['unique_id' => 'login'])->order('id DESC')->find());
                return $this->fetch();
            }
        }
    }

    /**
     * 注销
     */
    public function logout()
    {
        User::logout();
        $this->redirect('/');
    }

    /**
     * 注册发短信
     */
    public function reg_sms()
    {
        if ($this->request->isPost()) {

            //验证码
            if (!captcha_check($this->request->post('verify'), 1, config('captcha'))) {
                $this->error('您填写的图形验证码不正确，请重新输入！');
            }

            $phone = $this->request->post('phone', '');

            if (!checkPhone($phone)) {
                $this->error('大陆手机号格式不正确！');
            }

            if (db('user')->where(['phone' => $phone])->count() > 0) {
                $this->error('此号码已注册！');
            }

            $result = SendLogic::smsCode($phone, config('sms_reg_tmp_id'), __METHOD__);

            if (is_array($result) && $result['code'] == 1) {
                $this->success($result['msg']);
            } else {
                $this->error($result['msg']);
            }
        }

        $this->redirect('/');
    }

    /**
     * 找回密码 - 发短息
     * @return \think\response\Json
     */
    public function find_sms()
    {
        if ($this->request->isPost()) {

            $phone = $this->request->post('phone', '');

            //数据验证
            if (!captcha_check($this->request->post('verify'), 2, config('captcha'))) {
                $this->error('您填写的图形验证码不正确，请重新输入！');
            }

            if (!checkphone($phone)) {
                $this->error('大陆手机号格式不正确！');
            }

            if (Db::name('user')->where(array('phone' => $phone))->count() <= 0) {
                $this->error('大陆手机号未注册！');
            }

            $result = SendLogic::smsCode($phone, config('sms_find_pass_tmp_id'), __METHOD__);

            if (is_array($result) && $result['code'] == 1) {
                $this->success($result['msg']);
            } else {
                $this->error($result['msg']);
            }
        }

        $this->redirect('/');
    }

    /**
     * 找回密码
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function find()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (!captcha_check($data['verify'], 2, config('captcha'))) {
                $this->error('您填写的图形验证码不正确，请重新输入！');
            }

            if (!checkSms($data['phone'], $data['scode'])) {
                $this->error('短信验证码不正确，请重新输入');
            }

            if ($data['password1'] !== $data['password2']) {
                $this->error('确认密码和密码不同！', '');
            }

            $result = User::resets($data['phone'], $data['password1']);

            if (is_array($result) && $result['code'] == 1) {
                $this->success($result['msg'], 'login');
            } else {
                $this->success($result['msg']);
            }
        }

        return $this->fetch();
    }
}
